/**
 * Created by ZY on 2017/11/10
 */
let {feDeploy} = require('../../conf'),
  request = require('request'),
  util = require('../helper/util'),
  cst = require('../../conf/const'),
  errCode = require('../../conf/errorCode');
const INTEGER_REGEXP = /^\d+$/;
var isLogin = (req, res) => {
  return (
    req.signedCookies &&
    INTEGER_REGEXP.test(req.signedCookies[cst.LOGIN_SIGNATURE])
  );
};

exports.index = function(req, res, next) {
  res.render('index', {
    domain: feDeploy.domain,
  });
};

exports.login = function(req, res, next) {
  if (isLogin(req, res)) {
    return res.redirect('/');
  }
  res.render('login', {
    domain: feDeploy.domain,
  });
};

exports.upload = function(req, res, next) {
  if (!req.body.fileName || !req.body.file) {
    return util.getHandle(req, res, errCode.UPLOAD_IMG_TO_DFS)({
      errNo: errCode.LESS_OF_DATA_ERROR,
    });
  }
  console.log(req.body.file, req.body.fileName);

  let sign_file1 = req.body.fileName,
    file = req.body.file,
    file1 = new Buffer(file, 'base64'),
    url = 'http://innerupload.sogou/http_upload?appid=11070001';
  request.post({url, formData: {file1, sign_file1}}, function(
    err,
    result,
    body,
  ) {
    if (err) {
      return util.getHandle(req, res, errCode.UPLOAD_IMG_TO_DFS)({
        errNo: errCode.UPLOAD_IMG_TO_DFS,
      });
    }
    return util.getHandle(req, res, errCode.UPLOAD_IMG_TO_DFS)(
      null,
      JSON.parse(body),
    );
  });
};
